import { useAuth } from "./AuthContext.jsx";
import { useState, useEffect } from "react";

export default function Comments({ event_id, comments: initialComments = [], isTopLevel = true }) {
    const { authInfo } = useAuth();
    const [comments, setComments] = useState(initialComments);
    const [newComment, setNewComment] = useState({
        event_id,
        content: "",
        parent_id: null,
        user_id: authInfo?.user?.id || null,
    });

    useEffect(() => {
        if (isTopLevel) getComments();
        else setComments(initialComments); // 嵌套层使用传入的 comments
    }, [event_id, isTopLevel, initialComments]);

    async function getComments() {
        try {
            const res = await fetch(`http://127.0.0.1:8000/api/v1/events/${event_id}/comments`, {
                headers: {
                    "X-Request-ID": authInfo?.token_uuid || "",
                    "Authorization": authInfo ? `Bearer ${authInfo.token}` : "",
                },
            });
            if (res.status === 200) {
                const data = (await res.json()).data;
                setComments(data.event.comments);
            } else {
                console.error("Failed to fetch comments:", await res.json());
            }
        } catch (error) {
            console.error("Error fetching comments:", error);
        }
    }

    async function createComment(e) {
        e.preventDefault();
        if (!authInfo) return alert("Please log in to comment");

        try {
            const res = await fetch("http://127.0.0.1:8000/api/v1/comments", {
                method: "POST",
                headers: {
                    "X-Request-ID": authInfo.token_uuid,
                    "Authorization": `Bearer ${authInfo.token}`,
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(newComment),
            });
            if (res.status === 201) {
                await getComments();
                setNewComment({ ...newComment, content: "" });
            } else {
                console.error("Failed to create comment:", await res.json());
            }
        } catch (error) {
            console.error("Error creating comment:", error);
        }
    }

    const addReply = (parentId, newReply) => {
        const updateComments = (comments) => {
            return comments.map((c) => {
                if (c.id === parentId) {
                    return { ...c, replies: [newReply, ...c.replies] };
                }
                if (c.replies?.length > 0) {
                    return { ...c, replies: updateComments(c.replies) };
                }
                return c;
            });
        };
        setComments(updateComments(comments));
    };

    return (
        <div className="bg-white p-6 rounded-lg shadow-md">
            {isTopLevel && (
                <h2 className="text-2xl font-bold text-gray-800 mb-4">Comments</h2>
            )}
            {isTopLevel && authInfo && (
                <form onSubmit={createComment} className="mb-6">
                    <textarea
                        onChange={(e) => setNewComment({ ...newComment, content: e.target.value })}
                        className="w-full p-2 border rounded resize-none"
                        rows="3"
                        placeholder="Write your comment..."
                        value={newComment.content}
                    />
                    <button
                        type="submit"
                        className="mt-2 bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
                    >
                        Submit
                    </button>
                </form>
            )}
            <div className="space-y-4">
                {comments.map((comment) => (
                    <Comment
                        key={comment.id}
                        comment={comment}
                        event_id={event_id}
                        addReply={addReply}
                    />
                ))}
            </div>
        </div>
    );
}

function Comment({ comment, event_id, addReply }) {
    const { authInfo } = useAuth();
    const [isReplying, setIsReplying] = useState(false);
    const [reply, setReply] = useState({
        event_id,
        content: "",
        parent_id: comment.id,
        user_id: authInfo?.user?.id || null,
    });

    const handleReplySubmit = async (e) => {
        e.preventDefault();
        if (!authInfo) return alert("Please log in to reply");

        try {
            const res = await fetch(`http://127.0.0.1:8000/api/v1/comments`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-Request-ID": authInfo.token_uuid,
                    "Authorization": `Bearer ${authInfo.token}`,
                },
                body: JSON.stringify(reply),
            });
            if (res.status === 201) {
                const data = (await res.json()).data;
                const comment = data.comment
                addReply(comment.id, comment);
                setReply({ ...reply, content: "" });
                setIsReplying(false);
            } else {
                console.error("Failed to submit reply:", await res.json());
            }
        } catch (error) {
            console.error("Error submitting reply:", error);
        }
    };

    return (
        <div className="border-b pb-4">
            <p className="text-gray-800">{comment.content}</p>
            <p className="text-sm text-gray-500">
                By {comment.user.name} on {new Date(comment.created_at).toLocaleString()}
            </p>
            {authInfo && (
                <button
                    onClick={() => setIsReplying(!isReplying)}
                    className="text-blue-500 hover:underline mt-1"
                >
                    Reply
                </button>
            )}
            {isReplying && (
                <form onSubmit={handleReplySubmit} className="mt-2">
                    <textarea
                        className="w-full p-2 border rounded resize-none"
                        rows="2"
                        placeholder="Write your reply..."
                        value={reply.content}
                        onChange={(e) => setReply({ ...reply, content: e.target.value })}
                    />
                    <div className="mt-2 flex space-x-2">
                        <button
                            type="submit"
                            className="bg-blue-500 text-white px-4 py-1 rounded hover:bg-blue-600"
                        >
                            Commit
                        </button>
                        <button
                            type="button"
                            onClick={() => setIsReplying(false)}
                            className="bg-red-500 text-white px-4 py-1 rounded hover:bg-red-600"
                        >
                            Cancel
                        </button>
                    </div>
                </form>
            )}
            {comment.replies?.length > 0 && (
                <div className="ml-2 mt-2 space-y-2">
                    <Comments event_id={event_id} comments={comment.replies} isTopLevel={false} />
                </div>
            )}
        </div>
    );
}